package com.mlh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.mlh.entity.LoginUser;
import com.mlh.entity.User;
import com.mlh.mapper.MenuMapper;
import com.mlh.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author 缪林辉
 * @date 2024/3/13 16:31
 * @DESCRIPTION
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    @SuppressWarnings("all")
    private UserMapper userMapper;
    @Autowired
    private MenuMapper mapper;

    @Override
    //UserDetails是SpringSecurity中的接口，专门用于用户信息的封装
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //通过用户名去数据库查询用户信息
        LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(User::getUserName,username);
        //从数据库中获取对应用户名的用户信息
        User user = userMapper.selectOne(lambdaQueryWrapper);
        //如果查询不到数据就通过抛出异常来给出提示
        if(Objects.isNull(user)){
            throw new RuntimeException("用户名或密码错误");
        }
        // 根据用户查询权限信息 添加到LoginUser中
        //先用写死来进行测试
        // List<String> list = new ArrayList<>(Arrays.asList("test"));
        //从数据库中获取权限信息
        List<String> permissionKeyList = mapper.selectPermsByUserId(user.getId());
        //将查询出来的用户信息封装到UserDetails中
        return new LoginUser(user,permissionKeyList);
    }
}
